<template>
  <view class="page" v-if="role !== null">
    <form :model="role" ref="form" class="form">
      <view class="form-view">
        <view class="group">
          <view class="field-view">
            <view class="field">
              <view class="field-title">
                <text>角色名称</text>
              </view>
              <view class="field-value" style="margin-top: 10rpx">
                <input
                  class="text-input input"
                  :disabled="!!role.id"
                  :class="[role.id ? 'disabled' : '']"
                  v-model="role.role_name"
                  placeholder="请输入角色名称"
                />
              </view>
            </view>
          </view>
          <view class="field-view">
            <view class="field">
              <view class="field-title">
                <text>权限</text>
              </view>
              <view class="field-value">
                <ly-tree
                  ref="tree"
                  wrapClass="tree"
                  :tree-data="permissionOptions"
                  node-key="id"
                  :showCheckbox="true"
                  :defaultCheckedKeys="defaultCheckedKeys"
                  @check-change="permissionCheckChange"
                  :defaultExpandAll="!role.enterpriseId"
                >
                </ly-tree>
              </view>
            </view>
          </view>
        </view>
        <view class="btn-view">
          <!-- <view
            v-if="isEdit"
            class="submit-btn btn-error"
            @click="showDeleteRoleConfrim = true"
            >删除</view
          > -->
          <view
            class="submit-btn btn"
            :class="[isEdit ? 'btn-primary' : 'btn-warning']"
            @click="submit"
            >确认{{ isEdit ? "保存" : "新增" }}</view
          >
        </view>
      </view>
    </form>

    <!-- <u-toast ref="uToast" />
    <u-modal
      v-model="showDeleteRoleConfrim"
      :title="'提示'"
      :content="'确定删除该角色吗'"
      :show-cancel-button="true"
      @confirm="deleteRole"
    ></u-modal> -->

    <Message ref="message"></Message>
  </view>
</template>

<script>
import detailModule from "@/common/mixins/detail-module";
import { getOperations } from "@/common/api/operation.js";
import { postRole, putRole, deleteRole } from "@/common/api/role.js";
import { mapState, mapActions } from "vuex";
export default {
  mixins: [detailModule],
  computed: {
    ...mapState("User", ["userInfo"]),
  },
  data() {
    return {
      role: {},
      isEdit: true,
      permissionOptions: [],
      defaultCheckedKeys: [],

      showDeleteRoleConfrim: false,
      mixinViewOptions: {
        getURL: "/acl/getUserAcl",
        isShowLoading: false,
        reachBottom: false,
        createdIsNeed: false,
        pullDown: false,
      },
    };
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    // this.$refs.form.setRules(this.rules);
  },
  onLoad(e) {
    this.getOperations();
    this.getUserInfo();
    let title = "角色编辑";
    this.retsetData(e);
    if (e.id) {
      this.dataForm.id = e.id;
      this.getDataInfo();
    } else {
      this.isEdit = false;
      title = "角色新增";
    }
    if (this.role && this.role.enterpriseId === null) {
      title = "角色查看";
    }
    uni.setNavigationBarTitle({
      title,
    });

    this.initData();
  },
  methods: {
    ...mapActions("User", ["getUserInfo"]),
    fetchComplete(err, data = {}) {
      let role_map = data.role_map || {};

      if (role_map.length) {
        this.defaultCheckedKeys = role_map;
      }
      console.log(this.defaultCheckedKeys, "?this.defaultCheckedKeys");
      // this.removeParentKeys(role_map);
    },
    initData() {},

    getOperations() {
      getOperations().then((res) => {
        let data = res.data || {};
        let arr = [];
        let children = [];
        for (let i in data) {
          if (Array.isArray(data[i].rule)) {
            children = (data[i].rule || []).map((c, cIndex) => {
              return {
                label: c.name,
                value: c.action,
                id: c.action,
              };
            });
          } else {
            children.length = 0;
          }

          arr.push({
            id: i,
            key: i,
            data: i,
            value: i,
            label: data[i].name ? data[i].name.name || data[i].name : "",
            children,
          });
        }
        console.log(arr, "??arr");

        this.permissionOptions = arr;
      });
    },

    permissionCheckChange(e) {
      let data = e.data.value;
    },
    retsetData(e) {
      this.role = {
        id: e.id || undefined,
        enterpriseId: this.userInfo.enterpriseId,
        clientSide: 1,
        role_name: e.name || "",
        action_map: "",
        menu_map: "",
        mark: "",
      };
    },
    submit() {
      // this.$refs.form.validate(async (valid) => {
      if (!this.dataForm.role_name)
        return this.message.error("角色名称不能为空");
      let permissionIds = [];
      // if (valid) {
      this.$refs.tree.getCheckedNodes(true, false).forEach((e, i, arr) => {
        permissionIds = arr.map((i) => i.value);
      });
      uni.showLoading({
        title: "新增/修改中",
      });
      if (!this.isEdit) {
        return postRole({
          ...this.role,
          name: this.role.role_name,
          role_map: permissionIds,
        })
          .then((res) => {
            uni.hideLoading();
            uni.$emit("refresh-permission-role-list", null);
            if (res.code !== this.$ERR_OK) {
              return this.message.error(res.message || "提交失败");
            }
            this.showModal({
              title: "提示",
              content: "提交成功,点击返回上一页",
              showCancel: false,
              success: (r) => {
                this.$Router.go(-1);
              },
            });
          })
          .catch(() => {
            uni.hideLoading();
          });
      } else {
        return putRole({
          ...this.role,
          name: this.role.role_name,
          role_map: permissionIds,
        })
          .then((res) => {
            uni.hideLoading();
            if (res.code !== this.$ERR_OK) {
              return this.message.error(res.message || "提交失败");
            }
            uni.$emit("refresh-permission-role-list", null);
            this.showModal({
              title: "提示",
              content: "提交成功,点击返回上一页",
              showCancel: false,
              success: (r) => {
                this.$Router.go(-1);
              },
            });
          })
          .catch(() => {
            uni.hideLoading();
          });
      }
      // }
      // });
    },
    deleteRole() {
      return deleteRole({ id: this.role.id })
        .then((res) => {
          uni.$emit("refresh-permission-role-list", null);
          this.message.success({
            title: "删除成功",
            duration: 3000,
            mask: true,
            complete: function () {
              setTimeout(function () {
                uni.navigateBack({
                  delta: 1,
                });
              }, 2500);
            },
          });
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
page,
.page {
  min-height: calc(100vh - var(--window-top));
  background: linear-gradient(180deg, #0d1523 0%, #102945 100%);
  color: #fff;
}

.form {
  padding-top: 0;

  .form-view {
    padding: 10rpx 24rpx;
  }

  .group {
    line-height: 76rpx;
    padding-top: 30rpx;

    &:first-child {
      padding-top: 0;
    }
    .group-title-view {
      position: relative;
      border-top-left-radius: 5rpx;
      border-top-right-radius: 5rpx;
      overflow: hidden;

      .bg {
        position: absolute;
        z-index: 1;
        width: 100%;
        height: 100%;
      }
      .group-title-icon {
        position: relative;
        z-index: 2;
        width: 24rpx;
        margin: 0 20rpx;
        vertical-align: middle;
      }
      .group-title {
        position: relative;
        z-index: 2;
        color: #fff;
        font-size: 28rpx;
      }
    }
    .field-view {
      display: flex;
      flex-direction: row;

      .field {
        padding-top: 10rpx;
        flex: 1;

        &:nth-child(2) {
          margin-left: 90rpx;
        }
        .field-title {
          font-size: 32rpx;
          color: color-default;
          padding: 16rpx 0;
          line-height: 1.6;
        }
        .field-value {
          /* border: 3rpx solid #eeeeee; */
          color: #fff;
          display: flex;
          flex-direction: row;
          /deep/ {
            .tree {
              padding: 0 0 30rpx;
            }
          }
          .text-input {
            flex: 1;
			background-color: #1A3156!important;
			border: none !important;
			color: #fff!important;
            &.disabled {
              background-color: #f6f6f6;
            }
          }
          .select-show {
            flex: 1;
            font-size: 26rpx !important;
            padding: 0 20rpx !important;

            &.text-disabled {
              background-color: #eee;

              &.icon {
                background-color: #eee !important;
              }
            }
          }
          .icon {
            padding-right: 14rpx;

            &.icon-disabled {
              background-color: #eee;
            }
          }
          .placeholder {
            color: rgb(192, 196, 204);
          }
        }
        /deep/ .u-border-bottom:after {
          border: 0 !important;
        }
      }
    }
  }
  .btn-view {
    display: flex;
    flex-direction: row;
    padding: 30rpx 0;

    .submit-btn {
      flex: 1;
      margin-right: 30rpx;
      text-align: center;
      line-height: 90rpx;
      font-weight: 700;
      border-radius: 10rpx;
      font-size: 36rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: bold;
      color: #ffffff;
      &:last-child {
        margin-right: 0;
      }
    }
    .btn-default {
      background-color: #5178af;
    }
    .btn-success {
      background-color: #4cd964;
    }
    .btn-warn {
      background-color: #f0ad4e;
    }
    .btn-error {
      background-color: #dd524d;
    }
  }
}

.input {
  height: 90rpx;
  background: #fff;
  border-radius: 10rpx;
  padding: 0 20rpx;
  border: 2rpx solid #eee;
}
</style>